var g_listDepartmentsRoles;
var departmentChangeFlg = false ;

function init_member_add(){
	setOption('420000','member_shi_administration');
	memberBindData('420000');
}

//function onShiAdministrationChange(regionCode,selectName){
//	changeShiItem(regionCode,selectName);
//	memberBindData(regionCode);
//}

//function onXianAdministrationChange(regionCode){
//	memberBindData(regionCode);
//}

function onShiAdministrationChange(regionCode,selectXianName,selectDepartmentName){
	changeShiItem(regionCode,selectXianName);
	onBindDepartments(regionCode,selectDepartmentName);
}

function onXianAdministrationChange(regionCode,selectDepartmentName){
	onBindDepartments(regionCode,selectDepartmentName);
}

function onBindDepartments(regionCode,selectName){
	var url="bindData_query.shtml";
	if(regionCode == null || regionCode=="-1")
		 regionCode ="420000";	
	url+="?code="+regionCode;
	$.get(url,function(data){
		data = $.parseJSON(data);
		g_listDepartmentsRoles=data;
		var listRoles=data.listRoles;
		var listDepartments = data.listDepartments;
	   bind_memberData(selectName,listDepartments);
	})
}

function memberBindData(regionCode){
	var url="bindData_query.shtml";
	if(regionCode == null || regionCode=="-1")
		 regionCode ="420000";	
	url+="?code="+regionCode;
	$.get(url,function(data){
		data = $.parseJSON(data);
		g_listDepartmentsRoles=data;
		var listRoles=data.listRoles;
		var listDepartments = data.listDepartments;
	   bind_memberData("selectRole",listRoles);
	   bind_memberData("selectDepartment",listDepartments);
	})
}

function bind_memberData(selectName,list){
	$("#"+selectName).empty();
	$.each(list,function(i,value){
		var listStr = "<option value="+value.id+">"+value.name+"</option>";
		$("#"+selectName).append($(listStr));
	})
}

function setSelectSelected(value,selectId){
	var select= $('#'+selectId);
	select.val(value);
}

function btnAddMemeber(){
   var memberName=$("#txtMemberAdd").val();
   
   if(!memberName){
	   alert("请输入成员名称");
	   return;
   }
   var memberDepartment=$("#selectDepartment").val();
   
   if(!memberDepartment){
	   alert("部门不能为空");
	   return;
   }
   
   var memberPsw=$(txtPsw).val();
   if(!memberPsw){
	   alert("必须输入密码");
   }
   
   var memberNickName=$(txtNickName).val();
   if(!memberNickName){
	   alert("必须输入登陆名称");
   }
   
   var memberRole=$("#selectRole").val();
   
   
	var levelCity=$('#member_shi_administration').val();
	var levelTown=$('#member_xian_administration').val();
	var regionCode = whatTheRegionCode(levelCity,levelTown);
	
   var url="member_add.shtml?member_name="+memberName+"&member_department_id="
   	+memberDepartment+"&member_role_id="+memberRole+"&member_psw="+memberPsw+"&member_nickname="+
   	memberNickName+"&code="+regionCode;
   
   $.get(encodeURI(url),function(data){
	   if(data=="true"){
		    $("#txtMemberAdd").val("");
		   	alert("添加成功");
	   }
	   else{
		   alert(data);
	   }
   })
}

function queryByName(){
	var membername= $("#txtMemberName").val();
	var url="member_query.shtml?"+"member_name="+membername+"&flag=byName";
	init_member_query(encodeURI(url));
}

function queryByRoleDepartment(){
	var departmentname=$("#txtDepartmentNameForMember").val();
	var rolename=$("#txtRoleNameForMember").val();
	var url="member_query.shtml?"+"department_name="+departmentname+"&role_name="+rolename+"&flag=bymix";
	init_member_query(encodeURI(url));
}

function init_member_query(url){
	//debugger
	if(!url){
		url="member_query.shtml?member_name=&flag=byName";
	}
	var department_cols =  [
	                        {display: '编号', name : 'id', width : 50, sortable : true, align: 'center',hide: false,toggle : false},
	                        {display: '登录名', name : 'member_empName', width : 100, sortable : false, align: 'center'},
	                        {display: '用户名', name : 'member_name', width : 100, sortable : false, align: 'center'},
	            			 {display: '部门', name : 'member_department', width : 150, sortable : true, align: 'center'},
	            			 {display: '角色', name : 'member_role', width : 150, sortable : true, align: 'center'},
	            			 {display: '备注', name : 'member_remark', width : 200, sortable : true, align: 'center'}
	            		     ];

	var department_buttons =   [
	           				 			{ name: '更新', displayname: '更新', bclass: 'modify',onpress:onMemberUpdate },
	           				 			{separator: true},
	           				 			{ name: '删除',displayname: '删除', bclass: 'delete',onpress:onMemberDelete }
	           				 			];
	var setting={
		   width: 930,
		   height: 150,
		   url: url,
		   dataType: 'json',
		   colModel :department_cols,
			buttons:department_buttons,
			errormsg: '发生异常',
			sortname: "id",
			sortorder: "desc",
			usepager: true,
			title: '人员列表',
			pagestat: '显示记录从{from}到{to}，总数{total}条',
			useRp: true, 
			rp: 10, 
			rpOptions: [10,10, 15, 20, 30, 40, 100],
			nomsg: '没有符合条件的记录存在',
			minColToggle: 1, 
			preProcess:onMemberPreProcess,
			showTableToggleBtn: false, 
			autoload: false,
			resizable: false, 
			pagetext: '页',
         outof: '共',
         findtext: '查找',
         pagestat: "当前显示记录{from}到{to}条，总{total}条",
			procmsg: '加载中, 请稍等 ...', 
			singleSelect:true
		  };
	var grid=$("#memberTable").flexigrid(setting);
	$("#memberTable").flexOptions(setting).flexReload();
}

function onMemberUpdate(com,grid){
	debugger;
	 var data = {};
	    var selected_count = $('.trSelected', grid).length;
	 
	    if (selected_count != 1) {
	        alert("请选择一条记录！");
	        return;
	    }
	    else {
	       
	        
	        data.member_name= $(".trSelected td>div", grid)[1].children[0].value;
	        data.member_empName= $(".trSelected td>div", grid)[2].children[0].value;
	        //data.member_department= $(".trSelected td>div", grid)[2].children[0].value;
	        debugger;
	        data.member_department = departmentChangeFlg?$("#query_selectDepartment").val():$(".trSelected td>div", grid)[3].children[0].name;
	        if(!data.member_department){
	        	alert("不允许部门为空值");
	        	return;
	        }
	        data.member_role= $(".trSelected td>div", grid)[4].children[0].value;
	        data.member_remark= $(".trSelected td>div", grid)[5].children[0].value;
	        data.id = parseInt($(".trSelected td>div", grid)[5].children[1].innerHTML);
	        $.post("member_update.shtml",{"data":JSON.stringify(data)},function(data){
	        	  if(data=="true"){
	      		    $("#txtMemberAdd").val("");
	      		    departmentChangeFlg = false;
	      		   	alert("更新成功");
	      		    $('#divForChangeDepartment').hide();
	      		    init_member_query();
	      	   }
	      	   else{
	      		   alert(data);
	      	   }
	        });
	    }
}

function onMemberDelete(com,grid){
	 var selected_count = $('.trSelected', grid).length;
	    if (selected_count != 1) {
	        alert("请选择一条记录！");
	        return;
	    }
	    else {
	    	var isDelete = confirm("你确定要删除这条记录吗？");
	    	if(!isDelete){
	    		return;
	    	}
	        var member_id = parseInt($(".trSelected td>div", grid)[5].children[1].innerHTML);;
	        var url = encodeURI("member_delete.shtml?member_id="+member_id);
	        $.get(url,function(data){
	        	if(data=="true"){
	        		alert("删除成功！");
	        		init_member_query("member_query.shtml?member_name=&flag=byName");
	        	}
	        	else{
	        		alert("删除失败！");
	        	}
	        });
	    }
}

function changeMemberDepartment(regionCode,memberName,departmentName,departmentId){
	departmentChangeFlg = true;
	$('#divForChangeDepartment').show();
	$('#displayMemberName').val(memberName);
	var lastTwoRegionCode = regionCode.substring(4,6);
	var middleTwoRegionCode = regionCode.substring(2,4);
	var cityRegionCode = regionCode.substring(0,4)+"00";
	setOption("420000",'query_shi_administration');
	setSltDefaultVal('query_shi_administration',cityRegionCode);
	if(lastTwoRegionCode != "00"){
		changeShiItem(cityRegionCode,"query_xian_administration");
		setSltDefaultVal('query_xian_administration',regionCode);
	}
	else{
		$("#query_xian_administration").val("-1");
	}
	
	var url="bindData_query.shtml";
	url+="?code="+regionCode;
	$.get(url,function(data){
		data = $.parseJSON(data);
		g_listDepartmentsRoles=data;
		var listRoles=data.listRoles;
		var listDepartments = data.listDepartments;
	   bind_memberData("query_selectDepartment",listDepartments);
	   setSelectSelected(departmentId,'query_selectDepartment');
	})
}

function onMemberPreProcess(data){
    var newData;
    debugger;
    if (data != null) {
        var rows = [];
        for (var i = 0; i < data.rows.length; i++) {
        	
            var cellContent = [];
            //cellContent.push("<div style='height:10px;' >" + data.rows[i].cell.id + "</div>");
            cellContent.push("<div style='height:10px;' >" + (i+1) + "</div>");
            cellContent.push("<input type='text' style='width:100px;height:20px;font-family:微软雅黑' value='" + data.rows[i].cell.member_name + "' />");
            cellContent.push("<input type='text' style='width:100px;height:20px;font-family:微软雅黑' value='" + data.rows[i].cell.member_empName + "' />");
           // cellContent.push("<input type='text' class='selectDepartment' style='width:150px;height:20px;font-family:微软雅黑' value='" + data.rows[i].cell.member_department + "' />");
           // cellContent.push("<input type='text' class='selectRole' style='width:150px;height:20px;font-family:微软雅黑' value='" + data.rows[i].cell.member_role + "' />");
         
//            var selectDepartmentsStr="<select style='width:150px;height:26px;font-family:微软雅黑'>";
//        	$.each(g_listDepartmentsRoles.listDepartments,function(index,value){
//        	
//        		if(value.name==data.rows[i].cell.member_department){
//        			selectDepartmentsStr += "<option value="+value.id+" selected>"+value.name+"</option>";
//        		}
//        		else{
//        			selectDepartmentsStr += "<option value="+value.id+">"+value.name+"</option>";
//        		}
//        	})
//        	selectDepartmentsStr +="</select>";
//             cellContent.push(selectDepartmentsStr);
            
            var memberRegionCode = data.rows[i].cell.member_regionCode;
            var memberName = data.rows[i].cell.member_name;
            var memberDepartmentName = data.rows[i].cell.member_department;
            var memberDepartmentId = data.rows[i].cell.member_department_id;
            var selectDepartmentsStr ="<input type='button' value='"+data.rows[i].cell.member_department+ "'"+
            " style='width:150px;height:26px;font-family:微软雅黑' onclick=changeMemberDepartment('"+memberRegionCode+
             "','"+memberName+"','"+memberDepartmentName+"',"+memberDepartmentId+") name='"+memberDepartmentId+"' />";
            cellContent.push(selectDepartmentsStr);
            
             var selectRolesStr="<select style='width:150px;height:26px;font-family:微软雅黑'/>";
          	$.each(g_listDepartmentsRoles.listRoles,function(index,value){
          		if(value.name==data.rows[i].cell.member_role){
          			selectRolesStr += "<option value="+value.id+" selected>"+value.name+"</option>";
        		}
          		else{
          			selectRolesStr += "<option value="+value.id+">"+value.name+"</option>";
          		}
        	})
        	selectRolesStr+="</select>";
            cellContent.push(selectRolesStr);
            
            cellContent.push("<input type='text' style='width:200px;height:20px;font-family:微软雅黑' value='" + data.rows[i].cell.member_remark + "' />" +
            "<div style='height:10px;display:none'  >" + data.rows[i].cell.id + "</div>");
            var content = {
                cell: cellContent
            };
            rows.push(content);
        }
        newData = {
            total: data.total,
            page: data.page,
            rows: rows
        };
        return newData;

    }
}


